package cn.itrip.common;

import cn.itrip.beans.pojo.ItripUser;


import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;


public class MailUtil {
    public static void sendAccountActivateEmail(ItripUser user, String uuid) {
        String from = user.getUserCode();
        Session session = getSession(from);

        MimeMessage message = new MimeMessage(session);

        try {
            message.setSubject("这是一封激活账号的邮件");
            message.setSentDate(new Date());
            //setFrom 表示用哪个邮箱发送邮件
            message.setFrom(new InternetAddress(from));
            /**
             * RecipientType.TO||BCC||CC
             *     TO表示主要接收人
             *     BCC表示秘密抄送人
             *     CC表示抄送人
             * InternetAddress  接收者的邮箱地址
             */
            message.setRecipient(RecipientType.TO, new InternetAddress(user.getUserCode()));

            message.setContent("这是激活码：" + GenerateLinkUtils.generateActivateLink(user, uuid), "text/html;charset=utf-8");
            Transport.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static Session getSession(final String from) {

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");//指定发送的邮箱的邮箱协议
        props.setProperty("mail.smtp.host", "smtp.163.com");//指定SMTP服务器
        props.setProperty("mail.smtp.port", "25");  //smtp是发信邮件服务器,端口是25
        props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP验证

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(from, "z15975346fk");
            }
        });
        return session;
    }
}

